#!/usr/bin/env python
# coding: iso-8859-15

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

import os
import shutil
from array import array
import gzip
import tarfile
import commands

# 1- Choose the kernel version and arch target
sKernelVer = "2.6.27"
sKernelArch = "i686"
# 2- Choose the modules folder to look for the modules
sModulesFolder = "/mnt/opendomo/lib/modules/2.6.27-00009-g5198e66/"

sEnv = os.getcwd()
sLocalRepository = sEnv+"/"+sKernelVer+"-"+sKernelArch

# -------------- Defines for USB ---------------
aUSBDevices = {
'0x00': 'per_interface', 
'0x01': 'audio', 
'0x02': 'comm', 
'0x03': 'hid', 
'0x05': 'physical', 
'0x06': 'still_image', 
'0x07': 'printer', 
'0x08': 'mass_storage', 
'0x09': 'hub', 
'0x0a': 'cdc_data', 
'0x0b': 'cscid', 
'0x0d': 'content_sec', 
'0x0e': 'video', 
'0xe0': 'wireless_controller', 
'0xef': 'misc', 
'0xfe': 'app_spec', 
'0xff': 'vendor_spec'
}
# USB File offsets
MODULE_NAME=0
ID_VENDOR=2
ID_PRODUCT=3
INT_CLASS_ID=9
INT_SUBCLASS_ID=10
# ----------------------------------------------

# Functions
def vCreateRepoUSB():

   global MODULE_NAME, ID_VENDOR, ID_PRODUCT, INT_CLASS_ID, INT_SUBCLASS_ID, \
   aModulesData, sModulesIndex2Repo, aUSBDevices, sModulesFolder,\
   sLocalRepository, sEnv, sKernelVer, sKernelArch

   sLocalRepositoryUSB = sLocalRepository + "/usb"
   sUSBModulesFile = sModulesFolder+"modules.usbmap"
   sModulesIndex2Repo = sLocalRepositoryUSB+"/index.txt"


   bModuleExists = False
   aModulesDone = {}

   sTarFileName = "od-usb-modules-"+sKernelVer+"-"+sKernelArch+".tar.gz"
   sDeviceType = ""

   # Check if the local repo exists
   if os.path.exists(sLocalRepository) == False:
      os.mkdir(sLocalRepository)
   if os.path.exists(sLocalRepositoryUSB) == False:
      os.mkdir(sLocalRepositoryUSB)

   f = open(sUSBModulesFile, 'r')
   f2 = open(sModulesIndex2Repo, 'w')

   for line in f:
      bModuleExists = False
      aModulesData = line.split()
      if aModulesData[0].find('#') != -1:
         continue

      #Choose the device type
      if aUSBDevices.has_key(aModulesData[INT_CLASS_ID]) == False:
         if aUSBDevices.has_key(aModulesData[INT_SUBCLASS_ID]) == False:
            sDeviceType = "unknown"
         else:
            sDeviceType = aUSBDevices[aModulesData[INT_SUBCLASS_ID]]
      else:
            sDeviceType = aUSBDevices[aModulesData[INT_CLASS_ID]]

      # We look for the module in the modules folder unless is already copied
      if aModulesDone.has_key(aModulesData[MODULE_NAME]+".ko") == False:

         for root, dirs, files in os.walk(sModulesFolder):
               for file in files:
                  # Found a match between file and the modules file
                  if file == aModulesData[MODULE_NAME]+".ko":
                     aModulesDone[file] = 1
                     bModuleExists = True
                     # We copy the file to the repository if not already exists
                     if os.path.exists(sLocalRepositoryUSB+"/"+file+".gz") == False:
                        # Create the tree structure
                        if os.path.exists(sLocalRepositoryUSB+"/"+sDeviceType) == False:
                           os.mkdir(sLocalRepositoryUSB+"/"+sDeviceType)

                        # Copy the module compressed to the repository
                        f_in = open(root+"/"+file, 'rb')
                        f_out = gzip.open(sLocalRepositoryUSB+"/"+sDeviceType+"/"+file+".gz", 'wb')
                        f_out.writelines(f_in)
                        f_out.close()
                        f_in.close()
      else:
         bModuleExists = True

      #Store info into the index text file
      if bModuleExists == True:
         f2.write(aModulesData[ID_VENDOR]+" "+aModulesData[ID_PRODUCT]+" "+
         aModulesData[INT_CLASS_ID]+" "+aModulesData[INT_SUBCLASS_ID]+" "+
         sDeviceType+"/"+aModulesData[MODULE_NAME]+".ko\n")

   
   cmd = "/bin/tar -C "+sEnv+" -cvzf "+sTarFileName+" "+sKernelVer+"-"+sKernelArch
   output = commands.getoutput(cmd)

   print '-'*40
   # test if the file is a valid tar file
   if tarfile.is_tarfile(sTarFileName):
      print "%s repository created, ready to upload..." % sTarFileName
   else:
      print "%s is not a valid tar file" % sTarFileName
   print '-'*40
   
   #if sLocalRepository != "":
   #   shutil.rmtree(sLocalRepository)

#----------------MAIN-------------------------


#TODO: Catch params to build the rest of the repositories
#Create Repository for USB Modules
vCreateRepoUSB()

